import {findDocLastFileById, getFileStream} from "@/api/exportFile";
import {Loading} from 'element-ui';

const exportFile = ({path, params, fileName, fileType, method = 'post'}) => {
  return new Promise((resolve, reject) => {
    let options = {
      fullscreen: true,
      body: true,
      text: '正在下载...'
    };
    let loadingInstance = Loading.service(options);
    try {
      getFileStream(method,{url: path, params}).then(res => {
        const blob = new Blob([res], {type: fileType});
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = fileName;
        a.style.display = "none";
        document.body.appendChild(a);
        a.click();
        URL.revokeObjectURL(a.href);
        document.body.removeChild(a);
        loadingInstance.close();
        resolve()
      }).catch(e => {
        loadingInstance.close();
      })
    } catch (e) {
      loadingInstance.close();
      reject()
    }
  })
};

const downFileByFileItem = (file,owner) =>{
  owner.$modal.confirm(`是否确认下载${file.fileName}?`).then(function () {
    let options = {
      fullscreen: true,
      body: true,
      text: '正在下载...'
    };
    let loadingInstance = Loading.service(options);
    findDocLastFileById({docId: file.fileId}).then(res => {
      let {data:{fileUrl}} = res
      downFileByFilePath(fileUrl,file.fileName)
    }).finally(e => {
      loadingInstance.close();
    });
  });

}

const downFileByFilePath = (filePath,fileName) =>{
  fetch(`/fileDown/${filePath}`,).then(res => res.blob().then(blob => {
    let a = document.createElement('a');
    let url = window.URL.createObjectURL(blob);
    let filename = fileName;
    a.href = url;
    a.download = filename;
    a.click();
    window.URL.revokeObjectURL(url);
    document.getElementById('status').innerHTML = '下载完成';
  }));
}

export {exportFile,downFileByFileItem,downFileByFilePath}
